package com.tct.worktimeboard.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class JsonUtil {
    /**
     * 成功后返回json
     */
    public static JSONObject toJsonData(Object object){
        JSONObject result = new JSONObject();
        result.put("status","success");
        result.put("data", object);
        return result;
    }

    public static JSONObject toJsonMessage(Object object){
        JSONObject result = new JSONObject();
        result.put("status","message");
        result.put("data", object);
        return result;
    }

    /**
     * 不需要返回data的成功方法
     */
    public static JSONObject toJsonData(){
        JSONObject result = new JSONObject();
        result.put("status","success");
        return result;
    }

    /**
     * 失败后返回信息
     */
    public static JSONObject toErrorData(String message){
        JSONObject result = new JSONObject();
        result.put("status","error");
        result.put("message",message);
        return result;
    }


    /**
     * 文件存在返回的方法
     */
    public static JSONObject toExistData(String keyName,Object object){
        JSONObject result = new JSONObject();
        result.put("status","exist");
        result.put(keyName,object);
        return result;
    }

    public static JSONObject toWaringData(String message){
        JSONObject result = new JSONObject();
        result.put("status","waring");
        result.put("message",message);
        return result;
    }


    /**
     * 将接口接收到的linkHashMap转化为实体类
     */
    public static Object toObjectByLinkMap(Class cls , Object old){
        String s = JSON.toJSONString(old);
        JSONObject json = JSON.parseObject(s);
        return json.toJavaObject(cls);
    }

    public static Object toObjectList(Class cls,List<Map<String,Object>> list){
        List<Object> res = new ArrayList<>();
        list.forEach(item -> {
            res.add(toObjectByLinkMap(cls,item));
        });
        return res;
    }

    public static String jsonString(String message){
        Map<String,String> result = new HashMap<>();
        result.put("status","error");
        result.put("message",message);
        return JSON.toJSONString(result);
    }

}
